package com.wht.sip.core.transmit.message;

import com.wht.sip.config.SipConfig;
import com.wht.sip.core.auth.DigestServerAuthenticationHelper;
import com.wht.sip.core.context.SipProcessorContext;
import com.wht.sip.core.transmit.SIPSender;
import com.wht.sip.core.transmit.model.Device;
import com.wht.sip.core.transmit.model.RemoteAddressInfo;
import com.wht.sip.utils.IpPortUtil;
import com.wht.sip.utils.SipUtils;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.message.SIPRequest;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Managed;

import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.header.AuthorizationHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Response;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;

/**
 * @author by HaiTao.Wang on 2025/9/15.
 */
@Slf4j
@Managed
public class RegisterMessageProcessor extends SipRequestProcessorHandle implements SipMessageProcessor {

    @Inject
    private SipConfig sipConfig;

    @Inject
    private SIPSender sipSender;

    @Init
    public void init() {
        SipProcessorContext.requestProcessor.put("REGISTER", this);
    }

    /**
     * 处理注册请求
     *
     * @param event 请求事件
     */
    @Override
    public void processRequest(RequestEvent event) {

        Response response;

        try {
            SIPRequest request = (SIPRequest) event.getRequest();

            // 注册标志
            boolean registerFlag = request.getExpires().getExpires() != 0;

            FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
            AddressImpl address = (AddressImpl) fromHeader.getAddress();
            SipUri uri = (SipUri) address.getURI();
            String deviceId = uri.getUser();

            ViaHeader reqViaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
            String transport = reqViaHeader.getTransport();

            //从请求中获取设备ip地址和端口号
            RemoteAddressInfo remoteAddressInfo = SipUtils.getRemoteAddressFromRequest(request, false);
            String requestAddress = remoteAddressInfo.getIp() + ":" + remoteAddressInfo.getPort();
            String title = registerFlag ? "[注册请求]" : "[注销请求]";
            log.info("{}设备：{}, 开始处理: {}", title, deviceId, requestAddress);

            //查询设备
            Device device = SipProcessorContext.deviceMap.get(deviceId);
            if (device != null) {
                device.setIp(remoteAddressInfo.getIp());
                device.setPort(remoteAddressInfo.getPort());
                device.setHostAddress(IpPortUtil.concatenateIpAndPort(remoteAddressInfo.getIp(), String.valueOf(remoteAddressInfo.getPort())));
                device.setLocalIp(request.getLocalAddress().getHostAddress());
                // 判断TCP还是UDP
                device.setTransport("TCP".equalsIgnoreCase(transport) ? "TCP" : "UDP");

            }

            AuthorizationHeader authHead = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
            if (authHead == null) {
                log.info("{} 设备：{}, 回复401: {}", title, deviceId, requestAddress);
                response = getMessageFactory().createResponse(Response.UNAUTHORIZED, request);
                new DigestServerAuthenticationHelper().generateChallenge(getHeaderFactory(), response, sipConfig.getDomain());
                sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
                return;
            }

            // 校验密码是否正确
            boolean passwordCorrect = new DigestServerAuthenticationHelper().doAuthenticatePlainTextPassword(request, sipConfig.getPassword());

            if (!passwordCorrect) {
                // 注册失败
                response = getMessageFactory().createResponse(Response.FORBIDDEN, request);
                response.setReasonPhrase("wrong password");
                log.info("{} 设备：{}, 密码/SIP服务器ID错误, 回复403: {}", title, deviceId, requestAddress);
                sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
                return;
            }

            // 携带授权头并且密码正确
            response = getMessageFactory().createResponse(Response.OK, request);

            if (request.getExpires() == null) {
                response = getMessageFactory().createResponse(Response.BAD_REQUEST, request);
                sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
                return;
            }

            // 添加Contact头
            response.addHeader(request.getHeader(ContactHeader.NAME));
            // 添加Expires头
            response.addHeader(request.getExpires());

            sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
            // 注册成功
            if (registerFlag) {
                if (device == null) {
                    device = new Device();
                    device.setStreamMode("TCP-PASSIVE");
                    device.setDeviceId(deviceId);
                } else {
                    device.setStreamMode("TCP-PASSIVE");
                }

                device.setIp(remoteAddressInfo.getIp());
                device.setPort(remoteAddressInfo.getPort());
                device.setHostAddress(IpPortUtil.concatenateIpAndPort(remoteAddressInfo.getIp(), String.valueOf(remoteAddressInfo.getPort())));
                device.setLocalIp(request.getLocalAddress().getHostAddress());
                device.setTransport("TCP".equalsIgnoreCase(transport) ? "TCP" : "UDP");
                // 保存/更新
                SipProcessorContext.deviceMap.put(deviceId, device);

                log.info("[注册成功] deviceId: {}->{}", deviceId, requestAddress);
            } else {
                SipProcessorContext.deviceMap.remove(deviceId);
                log.info("[注销成功] deviceId: {}->{}", deviceId, requestAddress);
            }

        } catch (SipException | NoSuchAlgorithmException | ParseException e) {
            log.error("未处理的异常 ", e);
        }

    }


}
